// 用于存储分类

import { topCategory } from '@/api/constants'
import { findCategory } from '@/api/category'
export default {
  namespaced: true,

  state () {
    return {
      // 分类信息集合  依赖 constants重新设置，保证初始化有数据
      List: topCategory.map(item => ({ name: item }))
    }
  },
  mutations: {
    setList (state, payload) {
      state.List = payload
    },
    // 定义 show 和 hide 的函数  控制当前分类二级分类的显示与隐藏
    show (state, item) {
      const currCategory = state.List.find(category => category.id === item.id)
      currCategory.open = true
    },
    hide (state, item) {
      const currCategory = state.List.find(category => category.id === item.id)
      currCategory.open = false
    }
  },
  actions: {
    async getList (ctx) {
      // 获取分类数据，修改分类数据
      const data = await findCategory()
      // 给每个分类添加控制二级分类显示与隐藏的数据
      data.result.forEach(top => { top.open = false })
      ctx.commit('setList', data.result)
    }
  }
}
